package com.koushikdutta.ion;

import com.example.ohosasynclibrary.async.util.LogUtil;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.utils.net.Uri;

import java.io.*;

public class UriUtils {
    private static final String SCHEME_DATA = "dataability";
    private static final String SCHEME_FILE = "file";
    private static final String SCHEME_HTTP = "http";
    private static final String SCHEME_HTTPS = "https";

    public static ImageSource uriToImageSource(Context context, Uri uri) {
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        if (isDataMediaUri(uri)) {
            return ImageSource.create(uriToInputStream(context, uri), options);
        } else if (isResourceUri(context, uri)) {
            return ImageSource.create(uriToResource(context, uri), options);
        } else if (isNetWorkUri(uri)) {
            return null;
        } else if (isFileUri(uri)) {
            return ImageSource.create(uriToFileInputStream(uri), options);
        } else if (isAssertUri(uri)) {
            return ImageSource.create(uriRawFile(context, uri), options);
        } else {
            return null;
        }
    }

    /**
     * 判断是否是media uri
     *
     * @param uri dataability:///media/***
     * @return 返回是与否
     */
    public static boolean isDataMediaUri(Uri uri) {
        if (uri.getDecodedPathList() != null) {
            if (uri.getDecodedPathList().size() > 0) {
                return uri.getScheme().equals(SCHEME_DATA) && uri.getEncodedAuthority().isEmpty() && uri.getDecodedPathList().get(0).equals("media");
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 返回是否是asset目录的uri
     *
     * @param uri dataability:///resources/rawfile/...
     * @return 返回是与否
     */
    public static boolean isAssertUri(Uri uri) {
        if (uri == null) {
            return false;
        }
        if (uri.getDecodedPathList() != null) {
            if (uri.getDecodedPathList().size() > 2) {
                return uri.getScheme().equals(SCHEME_DATA)
                        && uri.getEncodedAuthority().isEmpty()
                        && uri.getDecodedPathList().get(0).equals("resources")
                        && uri.getDecodedPathList().get(1).equals("rawfile");
            }
        }
        return false;
    }

    /**
     * 判断是否是资源文件的uri
     *
     * @param context 上下文
     * @param uri     dataability://bundleName/id
     * @return 是与否
     */
    public static boolean isResourceUri(Context context, Uri uri) {
        if (uri == null || uri.getScheme() == null) {
            return false;
        }
        return uri.getScheme().equals(SCHEME_DATA) && uri.getDecodedAuthority().equals(context.getBundleName());
    }

    /**
     * 返回是否是网络的uri
     *
     * @param uri http://www.***.com or https://www.***.com
     * @return 返回是与否
     */
    public static boolean isNetWorkUri(Uri uri) {
        return uri.getScheme().equals(SCHEME_HTTP) || uri.getScheme().equals(SCHEME_HTTPS);
    }

    /**
     * 判断是否是文件的uri
     *
     * @param uri file://...
     * @return 返回是与否
     */
    public static boolean isFileUri(Uri uri) {
        return uri.getScheme().equals(SCHEME_FILE);
    }

    private static FileInputStream uriToFileInputStream(Uri uri) {
        try {
            File file = new File(uri.getDecodedPath());
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
//            e.printStackTrace();
            LogUtil.error(IonRequestBuilder.class.getName(), e.getMessage());
        }
        return null;
    }

    public static FileDescriptor uriToInputStream(Context context, Uri uri) {
        try {
            return DataAbilityHelper.creator(context).openFile(uri, "r");
        } catch (DataAbilityRemoteException | FileNotFoundException e) {
//            e.printStackTrace();
            LogUtil.error(UriUtils.class.getName(), e.getMessage());
        }

        return null;
    }

    public static Resource uriToResource(Context context, Uri uri) {
        try {
            return context.getResourceManager().getResource(Integer.parseInt(uri.getLastPath()));
        } catch (NotExistException | IOException e) {
//            e.printStackTrace();
            LogUtil.error(UriUtils.class.getName(), e.getMessage());
        }
        return null;
    }

    public static Resource uriRawFile(Context context, Uri uri) {
        try {
            RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry("resources/rawfile/" + uri.getLastPath());
            return rawFileEntry.openRawFile();
        } catch (IOException e) {
//            e.printStackTrace();
            LogUtil.error(UriUtils.class.getName(), e.getMessage());
        }
        return null;
    }
}
